/**
 * 封装Request请求
 */
import axios from 'axios'
import Vue from 'vue'
import router from '../router'
import setting from '../setting'
import { getToken, logOut } from '../utils/auth'

const request = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? process.env.VUE_APP_API_URL + process.env.VUE_APP_API_ROOT : process.env.VUE_APP_API_ROOT
})

request.interceptors.request.use(
  request => {
    if (getToken() !== null) {
      request.headers[setting.app_token_key] = getToken()
    }
    return request
  },
  error => {
    throw error
  }
)

request.interceptors.response.use(
  response => {
    if (response.status === 200) {
      const { data } = response
      if (data.code === 401) {
        Vue.prototype.$msg.error(data.msg)
        logOut()
        return
      }
      return data
    } else {
      router.push({ name: `${response.status}` })
    }
  },
  error => {
    throw error
  }
)

export default request
